<script lang="ts" setup>
  import { watch, ref } from 'vue';
  import { useRouter, RouterView } from 'vue-router';
  import {
    IconHome,
    IconBook,
    IconComputer,
    IconQuestionCircle,
    IconGift,
  } from '@arco-design/web-vue/es/icon';
  interface CreatorMenu {
    title: string;
    key?: string;
    icon?: any;
    children?: CreatorMenu[];
  }
  const menus: CreatorMenu[] = [
    { title: '评论', key: 'CREATOR_HOME', icon: IconHome },
    {
      title: '赞和收藏',
      icon: IconBook,
    },
    {
      title: '新增粉丝',
      icon: IconComputer,
    },
    {
      title: '私信',
      icon: IconGift,
    },
    {
      title: '系统通知',
      icon: IconQuestionCircle,
    },
  ];

  const menuMap = new Map();
  const router = useRouter();
  const selectedKeys = ref<string[]>([]);

  travelMenus(menus);

  watch(
    router.currentRoute,
    ({ matched }) => {
      const matchedMenu = findMatchedMenu(matched);
      if (matchedMenu) {
        selectedKeys.value = [matchedMenu.key];
      }
    },
    { immediate: true },
  );
  watch(
    () => selectedKeys.value[0],
    (name) => {
      if (name !== router.currentRoute.value.name) {
        router.push({ name });
      }
    },
  );

  function travelMenus(menus) {
    menus.forEach((item) => {
      if (!item.children) {
        menuMap.set(item.key, item);
      } else {
        travelMenus(item.children);
      }
    });
  }

  function findMatchedMenu(matched) {
    for (const item of matched) {
      if (menuMap.has(item.name)) {
        return menuMap.get(item.name);
      }
    }
  }
</script>

<template>
  <div>
    <a-menu mode="horizontal" :default-selected-keys="['1']" class="rounded-[3px]">
      <a-menu-item v-for="item in menus" :key="item.key">{{ item.title }}</a-menu-item>
    </a-menu>
    <div class="mt-[20px] px-[50px]">
      <RouterView />
    </div>
  </div>
</template>
